//
//  WriteEntryViewController.m
//  MyVirtualDiary
//
//  Created by Alexander Wallis on 13.07.13.
//  Copyright (c) 2013 Alexander Wallis. All rights reserved.
//

#import "WriteEntryViewController.h"
#import "UserViewController.h"
#import "AppDelegate.h"

@interface WriteEntryViewController ()

@end

@implementation WriteEntryViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    NSLog(@"name: %@", self.date);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - private methods 
-(AppDelegate *)appDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

- (IBAction)cancel:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(IBAction)save:(id)sender{
    if ([self.entryTextField.text length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Please fill in an entry" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }else {
        NSManagedObjectContext *context = [[self appDelegate]managedObjectContext];
        User *user = (User*)[context existingObjectWithID:self.userID error:nil];
        Entry *entry = [NSEntityDescription insertNewObjectForEntityForName:@"Entry" inManagedObjectContext:context];
        entry.titel = self.titel;
        entry.date = self.date;
        
        [user addEntriesObject:entry];
        [entry setUser:user];
        
        NSError *error = nil;
        if (![context save:&error]) {
            NSLog(@"can't save: %@", [error userInfo]);
        }
    }
    UserViewController *userViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"UserViewController"];
    [self.navigationController presentViewController:userViewController animated:YES completion:nil];
}

-(IBAction)backgroundTouched:(id)sender{
    [self.entryTextField resignFirstResponder];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == self.entryTextField) {
        [self.entryTextField resignFirstResponder];
    }
    return NO; 
}
@end
